<%@page import="guestbook.Greeting"%>
<%@page import="guestbook.PMF"%>
<%@page import="java.util.Date"%>
<%@page import="com.google.appengine.api.users.User"%>
<%@ page import="java.util.List" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@page import="com.google.appengine.api.users.UserServiceFactory"%>
<%@page import="com.google.appengine.api.users.UserService"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title>Insert title here</title>
		<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
		
		<script language="javascript">

		function refreshpage()
		{
		window.location.reload();
		}
		
		</script>
	</head>
	<body>
		<%
			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
			
			if( user != null ) {
			
		%>
			<p>Hello, <%= user.getNickname() %>! (You can
				<a href="<%= userService.createLogoutURL( request.getRequestURI() ) %>">sign out</a>.) </p>
		<%
			} else {
		%>
		
			<p>Hello!
			<a href="<%= userService.createLoginURL( request.getRequestURI() ) %>">sign in</a>
			to include your name with greetings you post.</p>
			
		<% } %>
		
		<%
			PersistenceManager pm = PMF.get().getPersistenceManager();
			String query = "SELECT from " + Greeting.class.getName() + " order by date desc range 0,5";
		
			List<Greeting> greetings = (List<Greeting>)pm.newQuery( query ).execute();
			
			if( greetings.isEmpty() ) {
			
		%>
		
		<p>The guestBook has no messages.</p>
		<%
			} else {
				for( Greeting g : greetings ) {
					if( g.getUser() == null ) { 
		%>
		
		<p>An anonymous person wrote:</p>
		<%
					} else {
		%>
		<p><b><%= g.getUser().getNickname() %></b> wrote:</p>
		<%
					}
		%>
		<blockquote><%= g.getContent() %></blockquote> 
		<%
				}
			}
			pm.close();
		
		%>
		
		<form action="/sign" method="post" onsubmit="refreshpage();" >
			<div><textarea name="content" rows="3" cols="60"></textarea> </div>
			<div><input type="submit" value="Post Greeting" /></div>
		</form>
		
	</body>
</html>